import type { FC, ReactNode } from 'react'
import React, { memo } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, message } from 'antd'

import { PhoneWrapper } from '@/views/login/c-cpns/phone-pannel/style'
import { PhoneOutlined } from '@ant-design/icons'
import { useMyDispatch } from '@/store'
import { Status, VerifyType } from '@/global/constant'
import { encryptData } from '@/utils/encrypt'
import useEncrypt from '@/hooks/use-encrypt'
import { fetchLoginAction } from '@/store/module/login'
import { phoneValidator } from '@/utils/validator'
import { IGetCode } from '@/global/type'
import VerifyCodeButton from '@/components/verify-code-button'

interface IProps {
  children?: ReactNode
}

const PhonePannel: FC<IProps> = (props) => {
  const dispatch = useMyDispatch()
  const [publicKey] = useEncrypt()
  const navigate = useNavigate()
  const [phoneForm] = Form.useForm()

  /* 回调 */
  function onFinish(values: any) {
    const newValues = { ...values, loginMethod: 1, loginType: 'pc', flag: true }
    const loginParams = encryptData(publicKey, newValues)
    // 准备去登录
    if (loginParams) {
      dispatch(fetchLoginAction(loginParams)).then(() => {
        navigate('/main', { replace: true })
      })
    }
  }

  function getCodeClick() {
    const phone = phoneForm.getFieldValue('phone')
    // 验证手机号
    const isPass = phoneValidator(phone)
    if (!isPass) {
      message.open({
        type: 'info',
        content: '请输入正确的手机号'
      })
      return
    }
    // 获取验证码
    const config: IGetCode = { type: VerifyType.Phone, data: phone }
    return config
  }

  // const phoneValidator = (rule: Rule, value: string, callback: any) => {
  //   const reg =
  //     /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
  //   if (!reg.test(value)) callback('请输入正确的手机号!')
  //   else callback()
  // }

  return (
    <PhoneWrapper>
      <Form
        name="phone_login"
        form={phoneForm}
        validateTrigger="onBlur"
        onFinish={onFinish}
      >
        <Form.Item
          name="phone"
          rules={[
            { required: true, message: '手机号不能为空！' }
            // { validator: phoneValidator }
          ]}
        >
          <Input
            prefix={<PhoneOutlined className="site-form-item-icon" />}
            placeholder="手机号码"
          />
        </Form.Item>
        <Form.Item
          name="phoneCode"
          rules={[{ required: true, message: '请输入验证码！' }]}
        >
          <div className="code-wrapper">
            <Input placeholder="验证码" />
            <VerifyCodeButton onClick={getCodeClick} />
          </div>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </PhoneWrapper>
  )
}

export default memo(PhonePannel)
